package com.example.demo2Jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet("/update")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req. setCharacterEncoding ("utf-8") ;
        resp. setContentType ("text/html;charset=UTF-8") ;
        PrintWriter out = resp.getWriter();
        int id=Integer. parseInt (req.getParameter("id") ) ;
        String title=req. getParameter ("title") ;
        String author=req. getParameter ("author") ;
        int price=Integer.parseInt (req.getParameter ("price"));
        //1.加载驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2.获得数据库连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC", "root", "123456");
//3.执行SQL语句，实现增、删、改、查操作
            String sql = "update book set Title=?, Author=?, Price=? where Bookid=?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, title);
            pstmt.setString(2, author);
            pstmt.setInt(3, price);
            pstmt.setInt(4, id);
            int count = pstmt.executeUpdate();
            if (count > 0) {//4. 结果处理
                resp.sendRedirect("getbook");
                pstmt.close();
                conn.close(); //5.关闭连接
                out.flush();
                out.close();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
